package me.zhenqu.redis;

import java.util.Collections;
import java.util.WeakHashMap;

/**
 * Created at 11-7-5
 *
 * @author yonghui.chen
 */
public class ServerMonitor implements Runnable {
    private final static int every = 60; // 60s
    //    private WeakReference<MonitorJedisPool> pool;
    private WeakHashMap<String, MonitorJedisPool> pools;
    private static ServerMonitor instance = new ServerMonitor();

    private ServerMonitor() {
        pools = new WeakHashMap<String, MonitorJedisPool>();
        Collections.synchronizedMap(pools);
        Thread t = new Thread(this);
        t.setName("jedis-monitor");
        t.setDaemon(true);
        t.start();
    }

    public static ServerMonitor getMonitor() {
        return instance;
    }

    public void addPool(String server, MonitorJedisPool pool) {
        pools.put(server, pool);
    }
/*
    public ServerMonitor(MonitorJedisPool pool) {
        this.pool = new WeakReference<MonitorJedisPool>(pool);
    }
*/

    public void run() {
        while (true) {
            for (MonitorJedisPool pool : pools.values()) {
                if (pool != null) {
                    pool.check();
                }
            }
/*
            MonitorJedisPool jedisPool = pool.get();
            if (jedisPool == null) return;
            jedisPool.check();
*/
            try {
                Thread.sleep(every * 1000);
            } catch (InterruptedException ignored) {

            }
        }
    }
}
